import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert' as convert;
import 'bean/beans.dart';

Future<bool> saveNowUser(User _user) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool result;
  if (_user == null) {
    result = await prefs.setString("nowUser", null);
  } else {
    result = await prefs.setString("nowUser", convert.jsonEncode(_user));
  }
  return result;
}

Future<User> getNowUser() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var s = prefs.getString("nowUser");
  if (s == null) {
    return null;
  }
  return User.fromJson(convert.jsonDecode(s));
}

Future saveHistoryList(List<Book> books) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool result;
  if (books == null) {
    result = await prefs.setString("history", null);
  } else {
    result = await prefs.setString("history", convert.jsonEncode(books));
  }
  return result;
}

Future getHistoryList() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var s = prefs.getString("history");
  if (s == null) {
    return <Book>[];
  }
  var l = convert.jsonDecode(s);
  List<Book> list = [];
  l.forEach((v) {
    list.add(Book.fromJson(v));
  });
  return list;
}

Future<bool> saveNowPlayBook(Book book) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool result;
  if (book == null) {
    result = await prefs.setString("nowPlayBook", null);
  } else {
    result = await prefs.setString("nowPlayBook", convert.jsonEncode(book));
  }
  return result;
}

Future<Book> getNowPlayBook() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var s = prefs.getString("nowPlayBook");
  if (s == null) {
    return null;
  }
  return Book.fromJson(convert.jsonDecode(s));
}

Future<bool> saveNowPlayIndex(int index) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return await prefs.setInt("nowPlayIndex", index);
}

Future<int> getNowPlayIndex() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getInt("nowPlayIndex");
}
